package com.bawei.auth.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.redis.service.RedisService;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.remote.RemoteUserInfo;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;

/**
 * @Author：HaoYunde
 * @Package：com.bawei.auth.service
 * @Project：mall_cloud
 * @name：UserLoginService
 * @Date：2024/6/27 16:28
 */
@Component
public class UserLoginService {
    @Autowired
    private RemoteUserInfo remoteUserInfo;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String ACCESS_TOKEN="login_tokens:";


    public LoginUser login(String username, String password) {
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不能为空");
        }
        if(StringUtils.isEmpty(password)){
            throw new RuntimeException("密码不能为空");
        }
        R<CusUser> cusUserByName = remoteUserInfo.findCusUserByName(username);
        CusUser data = cusUserByName.getData();
        if(data==null){
            throw new RuntimeException("用户不存在，没有这个人");
        }
        if(!password.equals(data.getPassword())){
            throw new RuntimeException("密码不正确");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setCusUser(data);
        System.out.println(loginUser);
        return loginUser;
    }

    public R<CusUser> info() {
        String token = SecurityUtils.getToken();
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token空了");
        }
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        System.out.println(userKey);
        String o = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(o, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        return R.ok(cusUser);
    }
    private String getTokenKey(String key)
    {
        return ACCESS_TOKEN + key;
    }
}
